<template>
  <div class="commodity-list">
    <div class="items">
      <div class="item" v-for="commodity in commodities" :key="commodity.id">
        <img class="image" :src="commodity.imageUrl" />
        <div class="info">
          <div class="name">{{commodity.name}}</div>
          <div class="category">{{commodity.categoryNamePath}}</div>
        </div>
        <div class="operation">
          <Button type="primary" size="small" @click="goCommodityDetail(commodity.id)">编辑</Button>
        </div>
      </div>
    </div>
    <div class="page">
      <Page :current="pageNum" :pageSize="pageSize" show-total :total="total" @on-change="handlePageChange" />
    </div>
  </div>
</template>

<script>
import { pageCommodities } from '../../api/CommodityApi'

export default {
  data () {
    return {
      commodities: [],
      pageNum: 1,
      pageSize: 7,
      total: 0,
    }
  },
  methods: {
    async pageCommodities () {
      const resp = await pageCommodities(this.pageNum, this.pageSize)
      this.commodities = resp.list
      this.total = resp.total
    },
    handlePageChange (page) {
      this.$router.push({
        path: '/commodity_list',
        query: {
          page,
        },
      }).catch(e => {
        console.log(e)
      })
      this.pageNum = page
      this.pageCommodities()
    },
    goCommodityDetail (id) {
      this.$router.push({
        name: 'commodity_detail',
        params: {
          id,
        },
      })
    }
  },
  created () {
    const page = this.$route.query.page
    if (page) {
      this.pageNum = parseInt(page, 10) || 1
    }
    this.pageCommodities()
  }
}
</script>

<style lang="scss" src="./CommodityList.scss"></style>